<template>
  <div class="container">
    <el-dialog :title="curId ? '修改学科' : '新增学科'" :visible="dialogVisible" width="400px" @close="dialogClose" @open="dialogOpen">
      <!-- 表单 -->
      <el-form :model="ruleForm" :rules="rules" ref="dialogRef" label-width="80px" class="demo-ruleForm">
        <el-form-item label="学科名称" prop="subjectName">
          <el-input v-model="ruleForm.subjectName" placeholder="请输入学科名称"></el-input>
        </el-form-item>
        <el-form-item label="是否显示" prop="isFrontDisplay">
          <el-switch v-model="ruleForm.isFrontDisplay" :active-value="1" :inactive-value="0" active-color="#13ce66" inactive-color="#ff4949" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogClose">取 消</el-button>
        <el-button type="primary" @click="okBtn">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { add, detail, update } from '@/api/hmmm/subjects'
export default {
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    },
    curId: {
      type: [String, Number],
      required: true
    }
  },
  data() {
    return {
      // 弹窗数据
      ruleForm: {
        subjectName: '',
        isFrontDisplay: 1
      },
      // 弹窗验证
      rules: {
        subjectName: [
          {
            required: true,
            message: '请输入学科名称',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  methods: {
    // 弹窗确认
    okBtn() {
      this.$refs.dialogRef.validate(async (valid) => {
        if (!valid) return
        if (this.ruleForm.creatorID) {
          // 修改
          await update(this.ruleForm)
          this.$message.success('修改学科成功')
        } else {
          await add(this.ruleForm)
          this.$message.success('新增学科成功')
        }
        this.$emit('getSubjectList')
        this.$emit('dialogClose')
      })
    },
    // 弹窗打开时
    dialogOpen() {
      if (this.curId) {
        this.getDetail()
      }
    },
    // 获取学科详情
    async getDetail() {
      const res = await detail(this.curId)
      this.ruleForm = res.data
    },
    // 关闭弹窗
    dialogClose() {
      this.$emit('dialogClose')
      this.$refs.dialogRef.resetFields()
      this.ruleForm = {
        subjectName: '',
        isFrontDisplay: 1
      }
    }
  }
}
</script>

<style scoped lang='less'></style>
